package com.example.workapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.Manifest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class WiFiActivity extends AppCompatActivity {

    private static final String TAG = "WiFiActivity";
    private WifiP2pManager wifiP2pManager;
    private WifiP2pManager.Channel channel;
    private static final int PORT = 8888;
    private static final int REQUEST_PERMISSION = 1;
    private String TARGET_DEVICE_MAC_ADDRESSString;
    private Uri filePath;
    private  String username,filename;
    private BroadcastReceiver wifiP2pReceiver;
    private IntentFilter intentFilter;
    private boolean isTargetDeviceFound = false; // 标记是否已找到目标设备
    private ProgressBar progressBar;
    private  int flag;//flag==0传输文件；flag==1,editFIle;flag == 2,投屏；

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "进行wifi界面");
        setContentView(R.layout.activity_wifi);
        Toast.makeText(this, "进入wifi界面", Toast.LENGTH_SHORT).show();

        progressBar = findViewById(R.id.progressBar);
        progressBar.setMax(100);
        flag = getIntent().getIntExtra("flag", 0); // 如果 Intent 中没有 "flag"，则返回 0
        TARGET_DEVICE_MAC_ADDRESSString = getIntent().getStringExtra("TARGET_DEVICE_MAC_ADDRESS");
        if(flag == 0){
            filePath = getIntent().getParcelableExtra("FILE_PATH");
            Log.d(TAG, "文件路径: " + filePath);
        }else if (flag==1){
            filename=getIntent().getStringExtra("filename");
            username=getIntent().getStringExtra("username");
            Log.d(TAG,username+" "+filename);
        }


        // 检查权限
        checkPermissionsAndInitialize();
        // 设置广播接收器
        setupBroadcastReceiver();
    }

    private void setupBroadcastReceiver() {
        wifiP2pReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                //配对/解绑
                if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                    if (networkInfo != null && networkInfo.isConnected()) {
                        wifiP2pManager.requestConnectionInfo(channel, info -> {
                            if (info.groupFormed && !info.isGroupOwner) {
                                Log.d(TAG, "连接到Group Owner，开始文件传输");
                                String hostAddress = info.groupOwnerAddress.getHostAddress();
                                startClientSocketForFileTransfer(hostAddress, filePath);
                            }
                        });
                    }else if(networkInfo == null){
                        Log.d(TAG, "networkInfo为空");
                    }else{
                        Log.d(TAG, "连接GO失败");
                    }
                    //列表变化
                } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
                    if (ActivityCompat.checkSelfPermission(WiFiActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        wifiP2pManager.requestPeers(channel, peerListListener);
                    }
                }
            }
        };

        intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
    }
    private void checkPermissionsAndInitialize() {
        // 需要申请的权限列表
        String[] permissions = {
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.ACCESS_FINE_LOCATION
        };

        // Android 12 及以上版本需要额外申请 NEARBY_WIFI_DEVICES 权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            permissions = new String[]{
                    Manifest.permission.ACCESS_WIFI_STATE,
                    Manifest.permission.CHANGE_WIFI_STATE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.NEARBY_WIFI_DEVICES
            };
        }

        // 检查是否已经授予所有权限
        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (!allPermissionsGranted) {
            // 动态申请权限
            ActivityCompat.requestPermissions(this, permissions, REQUEST_PERMISSION);
        } else {
            // 权限已授予，初始化 Wi-Fi Direct
            initializeWifiDirect();
        }
    }

    private void initializeWifiDirect() {
        try {
            Log.d(TAG, "初始化 Wi-Fi Direct");
            wifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
            if (wifiP2pManager == null) {
                Toast.makeText(this, "无法获取 Wi-Fi P2P 服务", Toast.LENGTH_SHORT).show();
                return;
            }

            channel = wifiP2pManager.initialize(this, getMainLooper(), null);
            if (channel == null) {
                Toast.makeText(this, "Wi-Fi P2P Channel 初始化失败", Toast.LENGTH_SHORT).show();
                return;
            }

            // 检查 Wi-Fi 是否开启
            WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            if (!wifiManager.isWifiEnabled()) {
                Toast.makeText(this, "请先打开 Wi-Fi", Toast.LENGTH_SHORT).show();
                wifiManager.setWifiEnabled(true);
                new Handler().postDelayed(this::discoverPeers, 2000); // 延迟2秒等待Wi-Fi开启
                return;
            }

            // 检查设备支持
            if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)) {
                Toast.makeText(this, "此设备不支持 Wi-Fi Direct", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }

            discoverPeers();

        } catch (SecurityException e) {
            e.printStackTrace();
            Toast.makeText(this, "权限被拒绝: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private void discoverPeers() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "缺少定位权限", Toast.LENGTH_SHORT).show();
            return;
        }

        wifiP2pManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
//                Toast.makeText(WiFiActivity.this, "正在搜索设备", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "开始搜索设备");
            }

            @Override
            public void onFailure(int reason) {
                String errorMsg;
                switch (reason) {
                    case WifiP2pManager.ERROR:
                        errorMsg = "内部错误，可能缺少权限或Wi-Fi未开启";
                        break;
                    case WifiP2pManager.P2P_UNSUPPORTED:
                        errorMsg = "设备不支持 Wi-Fi P2P";
                        break;
                    case WifiP2pManager.BUSY:
                        errorMsg = "Wi-Fi P2P 服务忙碌";
                        break;
                    default:
                        errorMsg = "未知错误";
                }
//                Toast.makeText(WiFiActivity.this, "搜索设备失败: " + errorMsg, Toast.LENGTH_LONG).show();
                Log.d(TAG, "搜索设备失败，错误代码: " + reason + " - " + errorMsg);
            }
        });
    }

    private final WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
        @Override
        public void onPeersAvailable(WifiP2pDeviceList peerList) {
            // 如果已经找到目标设备并尝试连接，则不再重复连接
            if (isTargetDeviceFound) {
                Log.d(TAG, "已找到目标设备，不再重复连接");
                return;
            }
            Collection<WifiP2pDevice> peers = peerList.getDeviceList();
            Log.d(TAG, "发现 " + peers.size() + " 个设备");

            if (peers.size() == 0) {
                Log.d(TAG, "没有发现设备");
                return;
            }

            // 查找目标设备
            for (WifiP2pDevice device : peers) {
                Log.d(TAG, "设备: " + device.deviceName + " (" + device.deviceAddress + ")");

                if (device.deviceAddress.equals(TARGET_DEVICE_MAC_ADDRESSString)) {
                    Log.d(TAG, "找到目标设备: " + device.deviceName);
                    isTargetDeviceFound = true;

                    // 连接
                    WifiP2pConfig config = new WifiP2pConfig();
                    config.deviceAddress = device.deviceAddress;

                    // 连接到目标设备
                    if (ActivityCompat.checkSelfPermission(WiFiActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        wifiP2pManager.connect(channel, config, new WifiP2pManager.ActionListener() {
                            @Override
                            public void onSuccess() {
                                Toast.makeText(WiFiActivity.this, "正在连接到目标设备", Toast.LENGTH_SHORT).show();
                                Log.d(TAG, "正在连接到目标设备");

                                // 连接失败后，停止设备发现
                                wifiP2pManager.stopPeerDiscovery(channel, null);
                            }

                            @Override
                            public void onFailure(int reason) {
                                Toast.makeText(WiFiActivity.this, "连接失败，错误代码: " + reason, Toast.LENGTH_SHORT).show();
                                Log.d(TAG, "连接失败，错误代码: " + reason);
                            }
                        });
                    } else {
                        Toast.makeText(WiFiActivity.this, "没有获得权限，无法连接", Toast.LENGTH_SHORT).show();
                        // 连接失败后，停止设备发现
                        wifiP2pManager.stopPeerDiscovery(channel, null);
                    }
                    break;
                }
            }

            if (!isTargetDeviceFound) {
                Log.d(TAG, "未找到目标设备");
            }
        }
    };

    // 如果本机是客户端，连接到 Group Owner 并传输文件
    private void startClientSocketForFileTransfer(String targetIp, Uri filePath) {
        new Thread(() -> {
            int retryCount = 0;
            final int MAX_RETRIES = 3; // 最大重试次数
            final long RETRY_DELAY = 2000; // 重试间隔时间（毫秒）

            while (retryCount < MAX_RETRIES) {
                try {
                    // 连接到 Group Owner
                    Socket socket = new Socket(targetIp, PORT);
                    Log.d(TAG, "已连接到 Group Owner: " + targetIp);
                    if(flag == 0){
                        // 发送文件
                        sendFile(socket, filePath);
                    }else if(flag == 1){
                        //editFile
                        Intent webIntent=new Intent(WiFiActivity.this,WebActivity.class);
                        webIntent.putExtra("filename",filename);
                        webIntent.putExtra("username",username);

                        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        // 发送消息
                        writer.println(filename);
                        System.out.println("客户端发送消息: " + filename);
                        // 接收服务器的回复
                        String response = reader.readLine();
                        System.out.println("服务器回复: " + response);
                        socket.close();

                        webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(webIntent);

//                        Intent editIntent=new Intent(WiFiActivity.this,CollaborativeEditor.class);
//                        editIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(editIntent);

                    }else if(flag==2){
                        // 投屏
                        // 发起连接
                        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        // 发送消息
                        writer.println("ping");
                        System.out.println("客户端发送消息: " + "ping");
                        // 接收服务器的回复
                        String response = reader.readLine();
                        System.out.println("服务器回复: " + response);
                        socket.close();

                        // 检查安装与启动应用
                        ScreenTrans.installAndLaunchApp(WiFiActivity.this, "mirrorapp.android", "mirrorapp.apk");
//                        Intent videoTransIntent=new Intent(WiFiActivity.this, ScreenTrans.class);
//                        videoTransIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivity(videoTransIntent);
                    }

                    socket.close();
                    return; // 传输成功，退出重试循环
                } catch (IOException e) {
                    retryCount++;
                    Log.e(TAG, "连接失败，重试次数: " + retryCount + "/" + MAX_RETRIES, e);

                    if (retryCount < MAX_RETRIES) {
                        try {
                            Thread.sleep(RETRY_DELAY); // 延迟后重试
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                            break;
                        }
                    }
                }
            }

            // 所有重试均失败
            runOnUiThread(() -> Toast.makeText(WiFiActivity.this, "文件传输失败，请检查网络连接", Toast.LENGTH_SHORT).show());
        }).start();
    }

    // 整数转字节数组
    private static byte[] intToBytes(int value) {
        return ByteBuffer.allocate(4).putInt(value).array();
    }

    // 长整数转字节数组
    private static byte[] longToBytes(long value) {
        return ByteBuffer.allocate(8).putLong(value).array();
    }

    // 发送文件
    private void sendFile(Socket socket, Uri filePath) {
        int retryCount = 0;
        final int MAX_RETRIES = 3; // 最大重试次数

        while (retryCount < MAX_RETRIES) {
            try (OutputStream outputStream = socket.getOutputStream();
                 FileInputStream inputStream = (FileInputStream) getContentResolver().openInputStream(filePath)) {

                // 发送 MIME 类型
                String mimeType = getContentResolver().getType(filePath);
                if (mimeType == null) {
                    mimeType = "application/octet-stream"; // 默认 MIME 类型
                }
                byte[] mimeTypeBytes = mimeType.getBytes(StandardCharsets.UTF_8);
                outputStream.write(intToBytes(mimeTypeBytes.length)); // 发送 MIME 类型长度
                outputStream.write(mimeTypeBytes); // 发送 MIME 类型内容

                // 发送文件大小
                long fileSize = getContentResolver().openAssetFileDescriptor(filePath, "r").getLength();
                outputStream.write(longToBytes(fileSize));
                Log.d(TAG, "发送文件类型: " + mimeType + "，大小: " + fileSize + " 字节");

                // 发送文件内容
                byte[] buffer = new byte[1024];
                int bytesRead;
                long totalBytesRead = 0;

                // 更新进度条最大值
                runOnUiThread(() -> progressBar.setVisibility(View.VISIBLE));

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    if (socket.isConnected()) {
                        outputStream.write(buffer, 0, bytesRead);
                        totalBytesRead += bytesRead;
                        // 每次发送后刷新缓冲区
                        outputStream.flush();
                        Log.d(TAG, "已发送: " + totalBytesRead + "/" + fileSize + " 字节");
                        final int progress = (fileSize > 0) ? (int) ((totalBytesRead * 100) / fileSize) : 0;
                        runOnUiThread(() -> progressBar.setProgress(progress));
                    } else {
                        throw new IOException("Socket 已关闭或断开连接");
                    }
                }

                outputStream.flush();
                Log.d(TAG, "文件发送完成");
                runOnUiThread(() -> progressBar.setVisibility(View.GONE));
                // 显示成功弹窗
                runOnUiThread(() -> showFileSendedDialog());
                return; // 传输成功，退出重试循环

            } catch (IOException e) {
                retryCount++;
                Log.e(TAG, "文件传输失败，重试次数: " + retryCount + "/" + MAX_RETRIES, e);

                if (retryCount >= MAX_RETRIES) {
                    runOnUiThread(() -> Toast.makeText(WiFiActivity.this, "文件传输失败，请重试", Toast.LENGTH_SHORT).show());
                }
            } catch (Exception e) {
                Log.e(TAG, "未知错误: " + e.getMessage());
                runOnUiThread(() -> Toast.makeText(WiFiActivity.this, "未知错误: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                break;
            }
        }
    }

    private void showFileSendedDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("文件发送成功");

        // 点击确认
        builder.setPositiveButton("确认", (dialog, which) -> {
            dialog.dismiss(); // 关闭弹窗
            finish(); // 关闭当前 Activity
        });

        // 显示弹窗
        builder.create().show();
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(wifiP2pReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(wifiP2pReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 解除注册 BroadcastReceiver
        if (wifiP2pReceiver != null) {
            unregisterReceiver(wifiP2pReceiver);
        }
    }

    // 处理权限请求结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }

            if (allPermissionsGranted) {
                // 权限已授予，初始化 Wi-Fi Direct
                initializeWifiDirect();
            } else {
                // 权限被拒绝，提示用户
                Toast.makeText(this, "需要权限才能使用 Wi-Fi Direct 功能", Toast.LENGTH_SHORT).show();
                finish(); // 关闭 Activity 或采取其他措施
            }
        }
    }
}